package com.example.demo.filter;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.example.demo.entity.LoginUser;
import com.example.demo.util.JWTUtil;
import com.example.demo.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class JWTFilter extends OncePerRequestFilter {

    @Autowired
    private RedisUtil redisUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader("Authorization");
//        System.out.println(request.getMethod());
//
//        if("OPTIONS".equals(request.getMethod())) {
//            filterChain.doFilter(request, response);
//            return;
//        }
        //如果token为空，进入下一个服务器
        if(token == null){
            filterChain.doFilter(request,response);
            return;
        }

        //验证token
        //todo:异常捕捉
        try {

            JWTUtil.verifyToken(token);

        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException("token不合法");
        }

        //获取用户信息
        Long userId = JWT.decode(token).getClaim("userId").asLong();

        LoginUser loginUser = redisUtil.getCacheObject("user:" + userId);

        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginUser,null,null);

        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        filterChain.doFilter(request,response);

    }
}
